<?php
namespace Realisation;

use Model\Process\ProcessInterface;
use Model\Loader\LoaderInterface;
use Model\Parser\ParserListInterface;
use Model\Saver\SaverInterface;
use Model\Entity\Url;
use Model\Saver\MessageSavedException;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerInterface;

/**
 * Description of Process
 *
 * @author pahhan
 */
class BaseProcess implements ProcessInterface, LoggerAwareInterface
{
    /**
     *
     * @var \Model\Loader\LoaderInterface
     */
    protected $loader;

    /**
     *
     * @var \Model\Saver\SaverInterface
     */
    protected $saver;

    /**
     *
     * @var \Model\Parser\ParserListInterface
     */
    protected $parser;

    /**
     *
     * @var LoggerAwareInterface
     */
    protected $logger;

    function __construct(LoaderInterface $loader, SaverInterface $saver, ParserListInterface $parser)
    {
        $this->loader = $loader;
        $this->saver = $saver;
        $this->parser = $parser;
    }

    public function run(Url $url_entity)
    {
        $url = $url_entity->getUrl();

        while ($url)
        {
            $crawler = $this->loader->getCrawler($url, $url_entity->getCharset());

            try {
                $messages = $this->parser->getMessages($crawler);
                $this->processMessages($messages, $url_entity);
                $this->saver->save($messages);
            }
            catch(MessageSavedException $e) {
                if( $this->logger ) {
                    $this->logger->info($e->getMessage(), array($url_entity->getKey() => 'process'));
                }
                break;
            }

            $url = $this->parser->getNextPageUrl($crawler);
        }
    }

    protected function processMessages(array $messages, Url $url_entity)
    {
        foreach ($messages as $message ) {
            $message->setUrlId($url_entity->getId());
            $message->setSiteId($url_entity->getSiteId());
            $message->setUpdatedAt(new \DateTime);
        }
    }

    public function setLogger(LoggerInterface $logger) {
        $this->logger = $logger;
    }


}

